import { TimerTickEvent } from "@sapi-game/gameComponent/common/timer/tickEvent";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { GameComponent } from "@sapi-game/main";
import { eleCatchState } from "../state";

export class ElevatorGameEndComponent extends GameComponent<eleCatchState> {
    private get liveMouses() {
        return this.context.mouse.filter((p) => p.isValid && p.lives > 0 && !p.bell);
    }

    override onAttach(): void {
        const timer = this.state.getComponent(Timer);
        this.subscribe(timer.events.tick, this.tick.bind(this));
    }

    tick(t: TimerTickEvent) {
        if (this.shouldEndGame(t)) {
            this.endGame();
        }
    }

    private shouldEndGame(t: TimerTickEvent): boolean {
        return (
            this.liveMouses.length === 0 ||
            this.context.cat.validSize === 0 ||
            t.remainingTime === 0
        );
    }

    endGame() {
        if (this.context.config.bellMode) {
            //盗铃模式
            const mousesWithBell = this.context.mouse.filter((p) => p.bell);
            if (mousesWithBell.length) {
                this.state.toEnd({
                    winTeam: this.context.mouse,
                    subtitle: `${mousesWithBell.length}个躲躲成功盗铃`,
                    msg: `游戏结束,胜者 : §e${mousesWithBell.map((p) => p.name).join("§r,")}`,
                });
            } else {
                this.state.toEnd({
                    winTeam: this.context.cat,
                    subtitle: "猫猫赢得了胜利",
                });
            }
        } else {
            //普通模式
            if (this.liveMouses.length) {
                this.state.toEnd({
                    winTeam: this.context.mouse,
                    subtitle: "躲躲获得了胜利",
                });
            } else {
                this.state.toEnd({
                    winTeam: this.context.cat,
                    subtitle: "猫猫抓获了所有躲躲",
                });
            }
        }
    }
}
